<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
          <el-option label="启用" value="enabled"></el-option>
          <el-option label="禁用" value="disabled"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="resetQuery">重置</el-button>
      </div>
      <el-table :data="filteredTableData" border class="eltable">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="gx_code" label="工序编码"></el-table-column>
        <el-table-column prop="gx_name" label="工序名称"></el-table-column>
        <el-table-column prop="gxlx_name" label="工序类型"></el-table-column>
        <el-table-column prop="gxzb_time" label="准备时间"></el-table-column>
        <el-table-column prop="gxbz_time" label="标准工时"></el-table-column>
        <el-table-column prop="bgfsname" label="报工方式"></el-table-column>
        <el-table-column prop="zjbz_code" label="检验标准"></el-table-column>
        <el-table-column label="启用">
          <template #default="{ row }">
            <el-switch :model-value="row.gx_state === 1" @change="toggleState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="text" @click="openDialog(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
      <el-form :model="formData" label-width="80px" :rules="formRules" ref="formRef">
        <el-row>
          <el-col :span="10">
            <el-form-item label="工序编码" prop="gx_code" >
              <el-input v-model="formData.gx_code" readonly placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="4"></el-col>
          <el-col :span="10">
            <el-form-item label="工序名称" prop="gx_name">
              <el-input v-model="formData.gx_name" placeholder="请输入工序名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="工序类型" prop="gxlx_code">
              <el-select v-model="formData.gxlx_code" placeholder="请选择工序类型">
                <el-option v-for="type in processTypeOptions" :key="type.dictionary_id" :label="type.dictionary_name"
                  :value="type.dictionary_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4"></el-col>
          <el-col :span="10">
            <el-form-item label="准备时间" prop="gxzb_time">
              <el-input v-model="formData.gxzb_time" placeholder="请输入准备时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="标准工时" prop="gxbz_time">
              <el-input v-model="formData.gxbz_time" placeholder="请输入标准工时" />
            </el-form-item>
          </el-col>
          <el-col :span="4"></el-col>
          <el-col :span="10">
            <el-form-item label="报工方式" prop="bgfs">
              <el-select v-model="formData.bgfs" placeholder="请选择报工方式">
                <el-option v-for="type in reportingMethodOptions" :key="type.dictionary_id"
                  :label="type.dictionary_name" :value="type.dictionary_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="检验标准" prop="zjbz_code">
              <el-select v-model="formData.zjbz_code" placeholder="请选择检验标准">
                <el-option v-for="option in queryData" :key="option.value" :label="option.label"
                  :value="option.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4"></el-col>
          <el-col :span="10"></el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, defineComponent, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 封装请求函数
const request = async (method, url, data = null) => {
  try {
    const response = await axios({ method, url, data });
    return response.data;
  } catch (error) {
    console.error(`请求 ${url} 失败:`, error);
    if (error.response) {
      throw new Error(`请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data.message || '未知错误'}`);
    } else {
      throw new Error(`请求失败: ${error.message}`);
    }
  }
};

export default defineComponent({
  setup() {
    // 数据状态
    const tableData = ref([]);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const formData = ref({
      gx_code: '',
      gx_name: '',
      gxlx_name: '',
      gxlx_code: 0,
      gxzb_time: 0,
      gxbz_time: 0,
      bgfs: 0,
      zjbz_code: '',
      gx_state: 1,
      is_deleted: 1,
      create_by: 0,
      create_time: '',
      update_by: 0,
      update_time: '',
    });

    const formRef = ref(null);

    // 工序类型
    const processTypeOptions = ref([]);
    // 报工方式
    const reportingMethodOptions = ref([]);
    // 质检标准
    const queryData = ref([
      { value: 'ZJBZ202502180001', label: '质检标准1' },
      { value: 'ZJBZ202502180002', label: '质检标准2' },
      { value: 'ZJBZ202502180003', label: '质检标准3' }
    ]);

    const formRules = {
      gx_name: [{ required: true, message: '工序名称不能为空', trigger: 'blur' }],
      gxlx_name: [{ required: true, message: '工序类型不能为空', trigger: 'blur' }],
    };

    // 生成工序编码
    const generateGxCode = () => {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const randomNum = String(Math.floor(Math.random() * 9000) + 1000);
      formData.value.gx_code = `GX${year}${month}${day}${randomNum}`;
    };

    // 获取数据
    const fetchData = async () => {
      try {
        const [mbdData, reportingData, processTypeData] = await Promise.all([
          request('get', '/api/MBD_GX/GetMbd_GX'),
          request('get', '/api/Dict/GetOneDict?id=10'),
          request('get', '/api/Dict/GetOneDict?id=11'),
        ]);
        tableData.value = mbdData;
        totalItems.value = mbdData.length;
        reportingMethodOptions.value = reportingData;
        processTypeOptions.value = processTypeData;
      } catch (error) {
        ElMessage.error(`数据获取失败: ${error.message}`);
      }
    };

    // 打开对话框
    const openDialog = (row) => {
      dialogVisible.value = true;
      dialogTitle.value = row ? '编辑工序定义' : '新增工序定义';
      if (row) {
        Object.assign(formData.value, row);
      } else {
        generateGxCode();
        Object.assign(formData.value, {
          gx_name: '',
          gxlx_name: '',
          gxlx_code: 39,
          gxzb_time: 0,
          gxbz_time: 0,
          bgfs: 38,
          zjbz_code: '',
          gx_state: 1,
          is_deleted: 1,
          create_by: 0,
          create_time: ''
        });
      }
    };

    // 提交表单
    const submitForm = async () => {
      const formRefValue = formRef.value;
      if (formRefValue) {
        formRefValue.validate(async (valid) => {
          if (valid) {
            // 处理数据格式
            formData.value.gxzb_time = parseInt(formData.value.gxzb_time) || 0;
            formData.value.gxbz_time = parseInt(formData.value.gxbz_time) || 0;
            formData.value.bgfs = parseInt(formData.value.bgfs) || 0;
            formData.value.create_by = parseInt(sessionStorage.getItem('u')) || 0;
            formData.value.create_time = new Date().toISOString();
            formData.value.update_by = parseInt(sessionStorage.getItem('u')) || 0;
            formData.value.update_time = new Date().toISOString();

            // 根据 gxlx_code 更新 gxlx_name
            const selectedType = processTypeOptions.value.find(
              (type) => type.dictionary_id === formData.value.gxlx_code
            );
            if (selectedType) {
              formData.value.gxlx_name = selectedType.dictionary_name;
            }

            try {
              const method = dialogTitle.value === '编辑工序定义' ? 'put' : 'post';
              const url = dialogTitle.value === '编辑工序定义' ? '/api/MBD_GX/UpdateMbd_GX' : '/api/MBD_GX/AddMbd_gx';
              await request(method, url, formData.value);
              ElMessage.success(dialogTitle.value === '编辑工序定义' ? '工序更新成功' : '工序新增成功');
              await fetchData();
              closeDialog();
            } catch (error) {
              ElMessage.error(`操作失败: ${error.message}`);
            }
          } else {
            ElMessage.error('表单数据不完整，请检查');
          }
        });
      }
    };

    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false;
      Object.assign(formData.value, {
        gx_code: '',
        gx_name: '',
        gxlx_name: '',
        gxzb_time: 0,
        gxbz_time: 0,
        bgfs: 0,
        zjbz_code: '',
        update_by: 0,
        update_time: '',
      });
    };

    // 查询数据
    const query = () => {
      console.log('查询条件:', searchTable.value, selectedFilter.value);
    };

    // 重置查询条件
    const resetQuery = () => {
      searchTable.value = '';
      selectedFilter.value = '';
    };

    // 删除行
    const deleteRow = (row) => {
      ElMessageBox.confirm('确定删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const url = `/api/MBD_GX/UpdateDelete?gx_code=${row.gx_code}&isdelete=0&update_by=${sessionStorage.getItem('u')}`;
            await request('put', url);
            ElMessage.success('删除成功!');
            await fetchData();
          } catch (error) {
            ElMessage.error(`删除失败: ${error.message}`);
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        });
    };

    // 处理当前页变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    // 过滤表格数据
    const filteredTableData = computed(() => {
      return tableData.value.filter((item) => {
        const matchesSearch = item.gx_name.includes(searchTable.value);
        const matchesFilter = selectedFilter.value
          ? item.gx_state === (selectedFilter.value === 'enabled' ? 1 : 0)
          : true;
        return matchesSearch && matchesFilter;
      });
    });

    // 切换状态
    const toggleState = async (row) => {
      const updatedStatus = row.gx_state === 1 ? 0 : 1;
      try {
        const url = `/api/MBD_GX/UpdateStatus?gx_code=${row.gx_code}&gx_state=${updatedStatus}&update_by=${sessionStorage.getItem('u')}`;
        await request('put', url);
        row.gx_state = updatedStatus;
        ElMessage.success('状态更新成功');
      } catch (error) {
        ElMessage.error(`状态更新失败: ${error.message}`);
      }
    };

    // 初始数据获取
    fetchData();

    return {
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      fetchData,
      query,
      resetQuery,
      deleteRow,
      handleCurrentChange,
      filteredTableData,
      toggleState,
      dialogVisible,
      dialogTitle,
      formData,
      formRules,
      openDialog,
      submitForm,
      closeDialog,
      reportingMethodOptions,
      processTypeOptions,
      formRef,
      queryData
    };
  },
});
</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
  background-color: rgba(255, 255, 255, 0.5); /* 设置表格背景色为白色，并带有50%的透明度 */
}
</style>